;org 0100h
;org 07c00h

%include "src/macro.asm"


extern start_entry
;jmp _start2
global _start2




[section .gdt]   ; Global segment description 
; GDT
LABEL_GDT: Descriptor 0, 0, 0
LABEL_DESC_CODE32: Descriptor 0, SegCode32Len-1, DA_C+DA_32   ; code segment 32 bit
LABEL_DESC_VIDEO:  Descriptor 0B8000h, 0FFFFh, DA_DRW        ; read/write
; GDT end

GdtLen equ $-LABEL_GDT          ; Length of GDT
GdtPtr dw GdtLen-1              ; Limit of GDT
       dd 0                     ; Base of GDT
       
; GDT Selector
SelectorCode32 equ LABEL_DESC_CODE32 - LABEL_GDT
SelectorVideo  equ LABEL_DESC_VIDEO  - LABEL_GDT


[section .s16]
[BITS 16]
_start2:
  mov ax, cs
  mov ds, ax
  mov es, ax
  mov ss, ax
  mov sp, 0100h


; call start_entry
  

LABEL_GOTO_PEMODE:
  ; Initialize 32 Code descriptor
  xor eax, eax
  mov ax,  cs
  shl eax, 4
  add eax, LABEL_SEG_CODE32
  mov word [LABEL_DESC_CODE32 + 2],    ax
  shr eax, 16
  mov byte [LABEL_DESC_CODE32 + 4],    al
  mov byte [LABEL_DESC_CODE32 + 7],    ah



  xor eax, eax
  mov ax, cs
  shl eax, 4
  add eax, LABEL_GDT
  mov dword [GdtPtr + 2], eax

  ; Load gdtr
  lgdt [GdtPtr]

  ; close interrupt
  cli

  ; open A20
  in al, 92h
  or al, 00000010b
  out 92h, al

  ; ready to switch protected mode 
  mov eax, cr0
  or eax, 1
  mov cr0, eax

  ; switch to protect mode
  jmp dword SelectorCode32:0




[section .text]
[BITS 32]
LABEL_SEG_CODE32:

  mov ax, SelectorVideo
  mov gs, ax
  
  mov ah, 0Fh
  mov al, 'Y'
  mov [gs:( ( 90 * 0 + 39 ) * 2 )], ax
  mov ah, 0Fh
  mov al, 'X'
  mov [gs:( ( 90 * 0 + 38 ) * 2 )], ax





;idle_keyboard:
;  mov ah, 1  ; check keydown
;  int 16h
;  jz idle_keyboard
;  mov ah, 0  ; read a key
;  int 16h
;  mov bx, 0  ; show char
;  mov ah, 0eh
;  int 10h
;  jmp idle_keyboard
  
  jmp $


SegCode32Len equ $ - LABEL_SEG_CODE32
; end [section .s32]




